import { prisma } from '@/lib/prisma/client'
import { NextResponse } from 'next/server'
import { format } from 'date-fns'
import { SceneHistory } from '@prisma/client'
import { ActionLog } from '@/types/actionLog'

export async function GET(
  request: Request,
  { params }: { params: { id: string } }
) {
  try {
    // 获取场景信息
    const scene = await prisma.scene.findUnique({
      where: { id: params.id }
    })

    if (!scene) {
      return NextResponse.json(
        { error: '场景不存在' },
        { status: 404 }
      )
    }

    // 获取所有历史记录
    const history = await prisma.sceneHistory.findMany({
      where: { sceneId: params.id },
      orderBy: { startTime: 'desc' }
    })

    // 生成CSV内容
    const csvHeaders = [
      '执行时间',
      '状态',
      '消息',
      '执行时长(ms)',
      '成功动作数',
      '失败动作数',
      '重试次数',
      '原始执行ID'
    ]

    const rows = history.map((record: SceneHistory) => {
      const actionLogs = JSON.parse(record.actionLogs as string)
      const successCount = actionLogs.filter((log: ActionLog) => log.status === 'SUCCESS').length
      const failureCount = actionLogs.filter((log: ActionLog) => log.status === 'FAILED').length

      return [
        format(record.startTime, 'yyyy-MM-dd HH:mm:ss'),
        record.status,
        record.message || '',
        record.duration,
        successCount,
        failureCount,
        record.retryCount,
        record.retryOf || ''
      ]
    })
    
    const csvContent = [
      csvHeaders.join(','),
      ...rows.map(row => row.join(','))
    ].join('\n')

    // 设置响应头
    const headers = new Headers()
    headers.set('Content-Type', 'text/csv; charset=utf-8')
    headers.set(
      'Content-Disposition',
      `attachment; filename="场景_${scene.name}_执行历史_${format(new Date(), 'yyyyMMdd_HHmmss')}.csv"`
    )

    return new Response('\ufeff' + csvContent, { headers })
  } catch (error) {
    return NextResponse.json(
      { error: '导出历史记录失败' },
      { status: 500 }
    )
  }
} 